<?php

class CapchaController extends AdminController
{
  public function init()
  {
    Yii::app()->user->loginUrl = '/admin/site/login';
  }

  /**
   * @return array action filters
   */
  public function filters()
  {
    return array(
            'accessControl', // perform access control for CRUD operations
    );
  }

  /**
   * Specifies the access control rules.
   * This method is used by the 'accessControl' filter.
   * @return array access control rules
   */
  public function accessRules()
  {
    return array(
    array('allow', // allow all users to perform 'index' and 'view' actions
                                        'actions' => array('view', 'list', 'create', 'update', 'delete', 'answer'),
                                        'roles' => array('member'),
    ),
    array('deny', // deny all users
                                        'users' => array('*'),
    ),
    );
  }

  /**
   * Displays a particular model.
   * @param integer $id the ID of the model to be displayed
   */
  public function actionView($id)
  {
    $this->render('view',array(
			'model'=>$this->loadModel($id),
    ));
  }

  /**
   * Creates a new model.
   * If creation is successful, the browser will be redirected to the 'view' page.
   */
  public function actionCreate()
  {
    $model=new Capcha;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Capcha']))
    {
      $model->attributes=$_POST['Capcha'];

      if ($model->save()) {
        Yii::app()->user->setFlash('success', "Tạo Capcha thành công");
        $this->redirect(array('list'));
      }
    }

    $this->render('create',array(
			'model'=>$model,
    ));
  }

  /**
   * Updates a particular model.
   * If update is successful, the browser will be redirected to the 'view' page.
   * @param integer $id the ID of the model to be updated
   */
  public function actionUpdate($id)
  {
    $model=$this->loadModel($id);

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Capcha']))
    {
      $model->attributes=$_POST['Capcha'];
      if ($model->save()) {
        Yii::app()->user->setFlash('success', "Cập nhật account thành công");
        $this->redirect(array('list') + $_GET);
      }
    }

    $this->render('update',array(
			'model'=>$model,
    ));
  }

  /**
   * Deletes a particular model.
   * If deletion is successful, the browser will be redirected to the 'admin' page.
   * @param integer $id the ID of the model to be deleted
   */
  public function actionDelete($id)
  {
    $this->loadModel($id)->delete();

    // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
    if (!isset($_GET['ajax'])) {
      Yii::app()->user->setFlash('success', "Xóa account thành công");
      $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('list'));
    }
  }

  /**
   * Manages all models.
   */
  public function actionList()
  {
    $criteria = new CDbCriteria();

    $criteria->addCondition('delete_flag =:delete_flag', 'AND');
    $params = array(':delete_flag' => Constants::DELETE_FLAG_FALSE);
    $searchData = array();

    if (isset($_GET['Capcha']) && sizeof($_GET['Capcha']) > 0) {
      $searchData = $_GET['Capcha'];

      foreach ($searchData as $key => $val) {
        if ($val != '') {
          $param = ':' . $key;
          $condtion = '';

          if ($key != 'create_date') {
            $condtion = $key . ' LIKE :' . $key . '';
            $params[$param] = '%' . $val . '%';
          } else {
            $condtion = $key . ' = :' . $key . '';
            $params[$param] = $val;
          }

          $criteria->addCondition($condtion, 'AND');
        }
      }
    }

    $criteria->params = $params;
    $count = Capcha::model()->count($criteria);

    $pages = new CPagination($count);

    // results per page
    $pages->pageSize = Constants::RECORD_OF_PAGE;
    $pages->applyLimit($criteria);

    $criteria->order = 'create_time DESC';
    $sort = new ExtSort('Capcha');
    $sort->applyOrder($criteria);

    $models = Capcha::model()->findAll($criteria);
    $searchModel=new Capcha('search');

    $crit = new CDbCriteria();
    $crit->addCondition('status = :status', 'AND');
    $crit->params = array(':status' => Constants::SITE_ACTIVE);
    $crit->order = 'sitename ASC';

    $siteList = Sites::model()->findAll($crit);

    if ($siteList) {
      $siteList = CHtml::listData($siteList, 'site_id', 'sitename');
    }

    $this->render('list',
    array('models' => $models,
            'pages' => $pages,
            'sort' => $sort,
            'searchModel' => $searchModel,
            'searchData' => $searchData,
            'siteList' => $siteList));
  }

  public function actionAnswer() {
   // var_dump($_POST);die;
      $captchaDao = new CapchaDAO();
      if (isset($_POST['content']) && !empty($_POST['content']) && isset($_POST['captchaId']) && !empty($_POST['captchaId'])) {
          $captchaDao->updateContent($_POST['captchaId'], $_POST['content']);
      }

      $captcha = $captchaDao->findNewest();

      $this->render('answer',array(
                      'capcha'=> $captcha,
      ));
  }

  /**
   * Returns the data model based on the primary key given in the GET variable.
   * If the data model is not found, an HTTP exception will be raised.
   * @param integer $id the ID of the model to be loaded
   * @return Capcha the loaded model
   * @throws CHttpException
   */
  public function loadModel($id)
  {
    $model=Capcha::model()->findByPk($id);
    if($model===null)
    throw new CHttpException(404,'The requested page does not exist.');
    return $model;
  }

  /**
   * Performs the AJAX validation.
   * @param Capcha $model the model to be validated
   */
  protected function performAjaxValidation($model)
  {
    if(isset($_POST['ajax']) && $_POST['ajax']==='capcha-form')
    {
      echo CActiveForm::validate($model);
      Yii::app()->end();
    }
  }
}
